define(['ionic', 'directives'], function() {
    angular.module('U9Mobile.directives')
        .directive('iframeKeyboardAttach', ['$ionicBody', function($ionicBody) {
            return function(scope, element, attr) {
                ionic.on('native.keyboardshow', onShow, window);
                ionic.on('native.keyboardhide', onHide, window);

                var isAppIFrame = element.hasClass('has-tabs'),
                    keyboardActiveElement;

                function onShow(e) {
                    var focusEls = angular.element(':focus', window.frames[attr.iframeKeyboardAttach].document);
                    if (focusEls.length !== 1) {
                        return;
                    }

                    keyboardActiveElement = focusEls.get(0);
                    
                    var elRect = keyboardActiveElement.getBoundingClientRect(),
                        keyboardHeight = e.keyboardHeight || e.detail.keyboardHeight,
                        clientHeight = element[0].clientHeight,
                        deltaBottom = clientHeight - elRect.bottom;
                    if (deltaBottom >= keyboardHeight) {
                        return;
                    }
                    var dist = deltaBottom - keyboardHeight - 8;
                    if (isAppIFrame) {
                        dist += 49;
                    }
                    translate(dist, 100);
                }

                function onHide() {
                    translate(0, 100);
                }

                function translate(to, speed) {
                    var style = $ionicBody.get().children[0].style;//element[0].style;
                    if (!style) return;

                    style.webkitTransitionDuration =
                        style.MozTransitionDuration =
                            style.msTransitionDuration =
                                style.OTransitionDuration =
                                    style.transitionDuration = speed + 'ms';

                    style.webkitTransform = 'translate(0,' + to + 'px)' + 'translateZ(0)';
                    style.msTransform =
                        style.MozTransform =
                            style.OTransform = 'translateY(' + to + 'px)';

                }

                scope.$on('$destroy', function() {
                    ionic.off('native.keyboardshow', onShow, window);
                    ionic.off('native.keyboardhide', onHide, window);

                    if (ionic.keyboard.isOpen) {
                        ionic.keyboard.hide();
                    }
                    if (isAppIFrame) {
                        keyboardActiveElement && keyboardActiveElement.blur();
                    }
                });
            };
        }]);
});
